$.fn.extend({
	removeRepeatOption : function() {
		return this.each(function() {
			if ($("option[value=" + $(this).val() + "]", $(this)).length > 1) {
				$("option[value=" + $(this).val() + "]", $(this)).last()
						.remove();
			}

		});

	},
	resetFrom : function() {
		$(this).click(function(){
			$("#searchDialogForm").find(':input').not(':button, :submit, :reset').val('').removeAttr('checked')
				.removeAttr('selected');
			$("#searchDialogForm").submit();
		});
	},
	orderBy: function(options){
		var op = $.extend({ targetType:"navTab", rel:"", asc:"asc", desc:"desc"}, options);
		return this.each(function(){
			var $this = $(this).css({cursor:"pointer"}).click(function(){				
				var orderField = $this.attr("orderField");
				var orderDirection = $this.hasClass(op.asc) ? op.desc : op.asc;
				if($this.hasClass("asc")){
					 orderDirection="desc";
				}else if($this.hasClass("desc")){
					 orderDirection="none";
				}else if($this.hasClass("none")){
					 orderDirection="asc";
				}
				
				dwzPageBreak({targetType:op.targetType, rel:op.rel, data:{pageNum:1,orderField: orderField, orderDirection: orderDirection}});
			});
			
		});
	},
	pagerForm: function(options){
		var op = $.extend({pagerForm$:"#pagerForm", parentBox:document}, options);
		var frag = '<input type="hidden" name="#name#" value="#value#" />';
		return this.each(function(){
			var $searchForm = $(this), $pagerForm = $(op.pagerForm$, op.parentBox);
			var actionUrl = $pagerForm.attr("action").replaceAll("#rel#", $searchForm.attr("action"));
			$pagerForm.attr("action", actionUrl);
			var pagerForm=$pagerForm.get(0);
			var searchForm=$searchForm.serializeArray();
			$.each(searchForm, function(i,n){
				if(pagerForm[n.name]){
					pagerForm[n.name].value=n.value;
				}else{
					var inputFrag = frag.replaceAll("#name#", n.name).replaceAll("#value#", n.value);
					$pagerForm.append(inputFrag);
				}
				
			});
		});
	},
	dialogAjaxTodo:function(){
		return this.each(function(){
			var $this = $(this);
			$this.click(function(event){
				var url = unescape($this.attr("href")).replaceTmById($(event.target).parents(".unitBox:first"));
				DWZ.debug(url);
				if (!url.isFinishedTm()) {
					alertMsg.error($this.attr("warn") || DWZ.msg("alertSelectMsg"));
					return false;
				}
				var title = $this.attr("title");
				if (title) {
					alertMsg.confirm(title, {
						okCall: function(){
							dialogAjaxTodo(url, $this.attr("callback"));
						}
					});
				} else {
					dialogAjaxTodo(url, $this.attr("callback"));
				}
				event.preventDefault();
			});
		});
	},
	navMenu:function(){
		return this.each(function(){
			var $box = $(this);
			$box.find("li>a").click(function(){
				var $a = $(this);
				$.get($a.attr("href"), {}, function(html){
					$("#sidebar").find(".accordion").remove().end().append(html).initUI();
					$box.find("li").removeClass("selected");
					$a.parent().addClass("selected");
					navTab.closeAllTab();
				});
				return false;
			});
		});
	}


	
});

// dwz.core.js DWZ.init
// dwz.ui.js initEnv
// dwz.ui.js initUI

// dwz.core.js ajaxUrl
// $.fn.initUI
// initUIextend
// dwz.ui.js initUI
function initUIextend(_box) {
	var $p = $(_box || document);
	if ($.fn.removeRepeatOption){
		$("select", $p).removeRepeatOption();
	}
	$(".resetFrom",$p).resetFrom();

	//dialogs
	$("a[target=searchDialog]", $p).each(function(){
		$(this).click(function(event){
			var $this = $(this);
			
			var $parent = $this.attr("targetType") == "dialog" ? $("body").data($this.attr("parentDialogId")) : navTab.getCurrentPanel();
			var $form = $("#pagerForm", $parent);
			var params = $form.serializeArray();
		
			var title = $this.attr("title") || $this.text();
			var rel = $this.attr("rel") || "_blank";
			var options = {};
			var w = $this.attr("width");
			var h = $this.attr("height");
			if (w) options.width = w;
			if (h) options.height = h;
			options.max = eval($this.attr("max") || "false");
			options.mask = eval($this.attr("mask") || "false");
			options.maxable = eval($this.attr("maxable") || "true");
			options.minable = eval($this.attr("minable") || "true");
			options.fresh = eval($this.attr("fresh") || "true");
			options.resizable = eval($this.attr("resizable") || "true");
			options.drawable = eval($this.attr("drawable") || "true");
			options.close = eval($this.attr("close") || "");
			options.param = params;

			var url = unescape($this.attr("href")).replaceTmById($(event.target).parents(".unitBox:first"));
			DWZ.debug(url);
			if (!url.isFinishedTm()) {
				alertMsg.error($this.attr("warn") || DWZ.msg("alertSelectMsg"));
				return false;
			}
			$.pdialog.openParams(url, rel, title, options);
			return false;
		});
	});
	if ($.isFunction(initUI))
		initUI(_box);
	$("a[target=dialogAjaxTodo]", $p).dialogAjaxTodo();
	$(".treeli",$p).contextMenu("treeMenu");
}
// dwz.core.js
$.fn.extend({
	initUI : function() {
		return this.each(function() {
			if ($.isFunction(initUIextend))
				initUIextend(this);
		});
	}
});
//====
//dwz.navTab.js
navTab.reload= function(url, options, method){
	var op = $.extend({data:{}, navTabId:"", callback:null}, options);
	var $tab = op.navTabId ? this._getTab(op.navTabId) : this._getTabs().eq(this._currentIndex);
	var $panel =  op.navTabId ? this.getPanel(op.navTabId) : this._getPanels().eq(this._currentIndex);
	
	if ($panel){
		if (!url) {
			url = $tab.attr("url");
		}
		if (url) {
			if ($tab.hasClass("external")) {
				navTab.openExternal(url, $panel);
			} else {
				if ($.isEmptyObject(op.data)) { //获取pagerForm参数
					var $pagerForm = $("#pagerForm", $panel);
					op.data = $pagerForm.size()>0 ? $pagerForm.serializeArray() : {};
				}
				
				$panel.ajaxUrl({
					//====
					type:method || "GET", url:url, data:op.data, callback:function(response){
						navTab._loadUrlCallback($panel);
						//===
						if ($.isFunction(op.callback)) op.callback(response,op);
					}
				});
			}
		}
	}
};

//====
//dwz.dialog.js
$.pdialog.reload=function(url, options, method){
	var op = $.extend({data:{}, dialogId:"", callback:null}, options);
	var dialog = (op.dialogId && $("body").data(op.dialogId)) || this._current;
	if (dialog){
		var jDContent = dialog.find(".dialogContent");
		jDContent.ajaxUrl({
			//===
			type:method||"GET", url:url, data:op.data, callback:function(response){
				jDContent.find("[layoutH]").layoutH(jDContent);
				$(".pageContent", dialog).width($(dialog).width()-14);
				$(":button.close", dialog).click(function(){
					$.pdialog.close(dialog);
					return false;
				});
				//===
				if ($.isFunction(op.callback)) op.callback(response,op);
			}
		});
	}
};
$.pdialog.openParams=function(url, dlgid, title, options) {
	var op = $.extend({},$.pdialog._op, options);
	var dialog = $("body").data(dlgid);
	//重复打开一个层
	if(dialog) {
		if(dialog.is(":hidden")) {
			dialog.show();
		}
		if(op.fresh || url != $(dialog).data("url")){
			dialog.data("url",url);
			if(options.param) dialog.data("param",options.param);
			dialog.find(".dialogHeader").find("h1").html(title);
			this.switchDialog(dialog);
			var jDContent = dialog.find(".dialogContent");
			jDContent.loadUrl(url, options.param, function(){
				jDContent.find("[layoutH]").layoutH(jDContent);
				$(".pageContent", dialog).width($(dialog).width()-14);
				$("button.close").click(function(){
					$.pdialog.close(dialog);
					return false;
				});
			});
		}
	
	} else { //打开一个全新的层
	
		$("body").append(DWZ.frag["dialogFrag"]);
		dialog = $(">.dialog:last-child", "body");
		dialog.data("id",dlgid);
		dialog.data("url",url);
		if(options.close) dialog.data("close",options.close);
		if(options.param) dialog.data("param",options.param);
		($.fn.bgiframe && dialog.bgiframe());
		
		dialog.find(".dialogHeader").find("h1").html(title);
		$(dialog).css("zIndex", ($.pdialog._zIndex+=2));
		$("div.shadow").css("zIndex", $.pdialog._zIndex - 3).show();
		$.pdialog._init(dialog, options);
		$(dialog).click(function(){
			$.pdialog.switchDialog(dialog);
		});
		
		if(op.resizable)
			dialog.jresize();
		if(op.drawable)
		 	dialog.dialogDrag();
		$("a.close", dialog).click(function(event){ 
			$.pdialog.close(dialog);
			return false;
		});
		if (op.maxable) {
			$("a.maximize", dialog).show().click(function(event){
				$.pdialog.switchDialog(dialog);
				$.pdialog.maxsize(dialog);
				dialog.jresize("destroy").dialogDrag("destroy");
				return false;
			});
		} else {
			$("a.maximize", dialog).hide();
		}
		$("a.restore", dialog).click(function(event){
			$.pdialog.restore(dialog);
			dialog.jresize().dialogDrag();
			return false;
		});
		if (op.minable) {
			$("a.minimize", dialog).show().click(function(event){
				$.pdialog.minimize(dialog);
				return false;
			});
		} else {
			$("a.minimize", dialog).hide();
		}
		$("div.dialogHeader a", dialog).mousedown(function(){
			return false;
		});
		$("div.dialogHeader", dialog).dblclick(function(){
			if($("a.restore",dialog).is(":hidden"))
				$("a.maximize",dialog).trigger("click");
			else
				$("a.restore",dialog).trigger("click");
		});
		if(op.max) {
//			$.pdialog.switchDialog(dialog);
			$.pdialog.maxsize(dialog);
			dialog.jresize("destroy").dialogDrag("destroy");
		}
		$("body").data(dlgid, dialog);
		$.pdialog._current = dialog;
		$.pdialog.attachShadow(dialog);
		//load data
		var jDContent = $(".dialogContent",dialog);
		jDContent.loadUrl(url, options.param, function(){
			jDContent.find("[layoutH]").layoutH(jDContent);
			$(".pageContent", dialog).width($(dialog).width()-14);
			$("button.close").click(function(){
				$.pdialog.close(dialog);
				return false;
			});
		});
	}
	if (op.mask) {
		$(dialog).css("zIndex", 1000);
		$("a.minimize",dialog).hide();
		$(dialog).data("mask", true);
		$("#dialogBackground").show();
	}else {
		//add a task to task bar
		if(op.minable) $.taskBar.addDialog(dlgid,title);
	}
};
//====
//dwz.ajax.js
function navTabPageBreak(args, rel){
	args["pageNum"]=0;
	dwzPageBreak({targetType:"navTab", rel:rel, data:args,callback:dwzPageBreakCallback});
}
function dialogPageBreak(args, rel){
	args["pageNum"]=0;
	dwzPageBreak({targetType:"dialog", rel:rel, data:args,callback:dwzPageBreakCallback});
}
function validateCallback(form, callback, confirmMsg) {
	var $form = $(form);

	if (!$form.valid()) {
		return false;
	}
	//===
	if($form.attr("_method")=="put" || $form.attr("_method")=="PUT"){
		if (form["_method"]) {
			form["_method"].value = "put";
		}else{
			$form.prepend("<input name='_method' value='put'  type='hidden'/>");
		}
		form.method="POST";
	}
	var _submitFn = function(){
		$.ajax({
			type: form.method || 'POST',
			url:$form.attr("action"),
			data:$form.serializeArray(),
			dataType:"json",
			cache: false,
			success: callback || DWZ.ajaxDone,
			error: DWZ.ajaxError
		});
	};
	
	if (confirmMsg) {
		alertMsg.confirm(confirmMsg, {okCall: _submitFn});
	} else {
		_submitFn();
	}
	
	return false;
}
function dwzPageBreakCallback(response, op) {
	//++获取提交的参数
	var orderField_v;
	$.each(op.data, function(i, n) {
		var s_a = n.name.split('.');
		if (s_a.length == 2)
			if (s_a[1].substring(0,4) == "sort") {
				var s_a_a=s_a[1].split("'");
				 orderField_v = s_a_a[1];
				if (n.value == "asc") {
					//$("th[orderField='" + orderField_v + "']",response.innerHTML).attr("class", "asc");
					$("th[orderField='" + orderField_v + "']").attr("class", "asc");
				} else if(n.value == "desc") {
					$("th[orderField='" + orderField_v + "']").attr("class", "desc");
				} else if(n.value == "") {
					$("th[orderField='" + orderField_v + "']").attr("class", "none");
				}
			}
	});
}
//====

//====
/**
 * 
 * @param {Object} args {pageNum:"",numPerPage:"",orderField:"",orderDirection:""}
 * @param String formId 分页表单选择器，非必填项默认值是 "pagerForm"
 */
//dwz.ajax.js
function _getPagerForm($parent, args) {
	
	var $form = $("#pagerForm", $parent);
	var form = $form.get(0);
	if (form) {
		var model = $form.attr("model");
		if (args["orderField"] && args["orderDirection"]) {
			var orderField = model + ".sort['"+args["orderField"]+"']";
			if (form[orderField]) {
				if(args["orderDirection"]=="none"){
					form[orderField].value="";
				}else{
					form[orderField].value = args["orderDirection"];
				}
			} else {
				$(form).append("<input type='hidden' value='" + args["orderDirection"] + "'  name=\"" + orderField+ "\" />");
			}
		}
		if (args["pageNum"] || args["pageNum"]==0){
			if(form[model + ".page"]){
				form[model + ".page"].value = args["pageNum"];
			}else{
				$(form).append("<input type='hidden' name='"+model+".page' value='"+args["pageNum"]+"' />");
			}
			
		}
		
		if (args["numPerPage"]){
			if(form[model + ".size"]){
				form[model + ".size"].value = args["numPerPage"];
			}else{
				$(form).append("<input type='hidden' name='"+model+".size' value='"+args["numPerPage"]+"' />");
			}
			
		}

		
	}
	return form;
}
/**
 * 处理navTab中的分页和排序
 * targetType: navTab 或 dialog
 * rel: 可选 用于局部刷新div id号
 * data: pagerForm参数 {pageNum:"n", numPerPage:"n", orderField:"xxx", orderDirection:""}
 * callback: 加载完成回调函数
 */
//dwz.ajax.js
function dwzPageBreak(options){
	var op = $.extend({ targetType:"navTab", rel:"", data:{pageNum:"", numPerPage:"", orderField:"", orderDirection:""}, callback:dwzPageBreakCallback}, options);
	var $parent = op.targetType == "dialog" ? $.pdialog.getCurrent() : navTab.getCurrentPanel();
	if (op.rel) {
		var $box = $parent.find("#" + op.rel);
		var form = _getPagerForm($box, op.data);
		if (form) {
			//===
			$box.ajaxUrl({
				type:$(form).attr("method")||"GET", url:$(form).attr("action"), data: $(form).serializeArray(), callback:function(){
					$box.find("[layoutH]").layoutH();
				}
			});
		}
	} else {
	
		var form = _getPagerForm($parent, op.data);
		var params = $(form).serializeArray();
		if (op.targetType == "dialog") {
			//===
			if (form) $.pdialog.reload($(form).attr("action"), {data: params, callback: op.callback},$(form).attr("method"));
		} else {
			//===
			if (form) navTab.reload($(form).attr("action"), {data: params, callback: op.callback},$(form).attr("method"));
		}
	}
}
//====
//====
function navTabSearch(form, navTabId){
	var $form = $(form);
	navTab.reload($form.attr('action'), {data: $(form).serializeArray(), navTabId:navTabId},$form.attr('method'));
	return false;
}
function dialogSearch(form){
	var $form = $(form);
	//===
	$.pdialog.reload($form.attr("action"), {data: $form.serializeArray()},$form.attr("method"));
	return false;
}
function navTabSearchDialog(form, navTabId){
	var $form = $(form);
	var $parent = navTab.getCurrentPanel();
	var pagerForm = $("#pagerForm", $parent).get(0);
	if (pagerForm) {
		var formserializeArray=$form.serializeArray();
		$.each(formserializeArray, function(i,n){
			if (pagerForm[n.name]) {
				pagerForm[n.name].value = n.value;
			} else {
				$(pagerForm).append("<input type='hidden' name='" + n.name+ "' value='" + n.value + "' />");
			}
		});
		
		var params = $form.serializeArray();
		navTab.reload($(pagerForm).attr("action"), {data: params,navTabId:navTabId,callback:dwzPageBreakCallback},$(pagerForm).attr("method"));
	}
	return false;
}
//====


//====

function dialogSearchDialog(form,parentDialogId){
	var $form = $(form);
	var $dialog = $("body").data(parentDialogId);
    var pagerForm = $("#pagerForm",$dialog).get(0);
	if (pagerForm) {
		var formserializeArray=$form.serializeArray();
		$.each(formserializeArray, function(i,n){
			if (pagerForm[n.name]) {
				pagerForm[n.name].value = n.value;
			} else {
				$(pagerForm).append("<input type='hidden' name='" + n.name+ "' value='" + n.value + "' />");
			}
		});
		
		var params = $form.serializeArray();
		$.pdialog.reload($(pagerForm).attr("action"), {data: params,dialogId:parentDialogId,callback:dwzPageBreakCallback},$(pagerForm).attr("method"));
	}
	return false;
}
//====

//====
/**
 * dialog上表单提交回调函数
 * 服务器转回dialog
 * 打开指定的dialog
 * 重载指定的dialog
 * 关闭指定的dialog
 */
function dialogAjaxTest(json){
	DWZ.ajaxDone(json);
	if (json.statusCode == DWZ.statusCode.ok){
		if (json.openId && json.forwardUrl && json.title){//打开新的指定dialog		
			var options = {};
			json.dialogWidth ? options.width = json.dialogWidth:options.width=900;
			json.dialogHeight ? options.height = json.dialogHeight:options.height=600;
			options.max = eval("false");
			options.mask = eval("false");
			options.maxable = eval("true");
			options.minable = eval("true");
			options.fresh = eval("true");
			options.resizable = eval("true");
			options.drawable = eval("true");
			options.close = eval("");
			options.param ="";	
			$.pdialog.open(unescape(json.forwardUrl),json.openId,json.title,options);
		}
		if (json.reloadId) {//重新载入指定dialog
            var $dialog = $("body").data(json.reloadId);
            var $pagerForm = $("#pagerForm",$dialog);
            var params = $pagerForm.size()>0 ? $pagerForm.serializeArray() : {}
            $.pdialog.reload($pagerForm.attr("action"), {data: params,dialogId:json.reloadId,callback:dwzPageBreakCallback},$pagerForm.attr("method"));
		}
		if (json.closeId) {//关闭指定dialog
			var $dialog = $("body").data(json.closeId);
			$.pdialog.close($dialog);
		}
		if ("closeCurrent" == json.callbackType) {
			$.pdialog.closeCurrent();
		}
	}
}
/**
 * dialog上的表单提交回调函数
 * 服务器转回navTabId，可以重新载入指定的navTab. statusCode=DWZ.statusCode.ok表示操作成功, 自动关闭当前dialog
 * 
 * form提交后返回json数据结构,json格式和navTabAjaxDone一致
 */
function newDialogAjaxDone(json){
	DWZ.ajaxDone(json);
	if (json.statusCode == DWZ.statusCode.ok){
		if (json.dialogId){
			if($("body").data(json.dialogId)){
				var $dialog = $("body").data(json.dialogId);
				var $pagerForm = $("#pagerForm",$dialog);
				$.pdialog.reload($pagerForm.attr("action"),{data: {l:1},dialogId:json.dialogId});
			}
		}else{
			var $pagerForm = $("#pagerForm", navTab.getCurrentPanel());
			navTab.reload($pagerForm.attr("action"), {data: {l:1}},$pagerForm.attr("method"));
		}
		if ("closeCurrent" == json.callbackType) {
			$.pdialog.closeCurrent();
		}
	}
}
function editDialogTree(json){
	DWZ.ajaxDone(json);
	if (json.statusCode == DWZ.statusCode.ok){
		if (json.dialogId){
			if($("body").data(json.dialogId)){
				var $dialog = $("body").data(json.dialogId);
				var $itree = $(".itree",$dialog);
				$.pdialog.reload($itree.attr("url"),{dialogId:json.dialogId});
			}
		}
		if ("closeCurrent" == json.callbackType) {
			$.pdialog.closeCurrent();
		}
	}
}
function editDialogAjaxDone(json){
	DWZ.ajaxDone(json);
	if (json.statusCode == DWZ.statusCode.ok){
		if (json.dialogId){
			if($("body").data(json.dialogId)){
				var $dialog = $("body").data(json.dialogId);
				var $pagerForm = $("#pagerForm",$dialog);
				$.pdialog.reload($pagerForm.attr("action"),{data:$pagerForm.serializeArray(),dialogId:json.dialogId});
			}
		}else{
			var $pagerForm = $("#pagerForm", navTab.getCurrentPanel());
			navTab.reload($pagerForm.attr("action"), {data:$pagerForm.serializeArray(),navTabId: json.targetId},$pagerForm.attr("method"));
		}
		if ("closeCurrent" == json.callbackType) {
			$.pdialog.closeCurrent();
		}
	}
}
//====
function navTabAjaxDone(json){
	DWZ.ajaxDone(json);
	if (json.statusCode == DWZ.statusCode.ok){
		if (json.navTabId){ //把指定navTab页面标记为需要“重新载入”。注意navTabId不能是当前navTab页面的
			navTab.reloadFlag(json.navTabId);
		} else { //重新载入当前navTab页面
			var $pagerForm = $("#pagerForm", navTab.getCurrentPanel());
			var args = $pagerForm.size()>0 ? $pagerForm.serializeArray() : {};
			//===
			dwzPageBreak({targetType:"navTab", rel:json.rel, data:args,callback:dwzPageBreakCallback});
		}
		
		if ("closeCurrent" == json.callbackType) {
			setTimeout(function(){navTab.closeCurrentTab(json.navTabId);}, 100);
		} else if ("forward" == json.callbackType) {
			navTab.reload(json.forwardUrl);
		} else if ("forwardConfirm" == json.callbackType) {
			alertMsg.confirm(json.confirmMsg || DWZ.msg("forwardConfirmMsg"), {
				okCall: function(){
					navTab.reload(json.forwardUrl);
				},
				cancelCall: function(){
					navTab.closeCurrentTab(json.navTabId);
				}
			});
		} else {
			navTab.getCurrentPanel().find(":input[initValue]").each(function(){
				var initVal = $(this).attr("initValue");
				$(this).val(initVal);
			});
		}
	}
}
function dialogAjaxDone(json){
	DWZ.ajaxDone(json);
	if (json.statusCode == DWZ.statusCode.ok){
		if (json.dialogId){
			if($("body").data(json.dialogId)){
				var $dialog = $("body").data(json.dialogId);
				var $pagerForm = $("#pagerForm",$dialog);
				var args = $pagerForm.size()>0 ? $pagerForm.serializeArray() : {};
				dwzPageBreak({targetType:"dialog", rel:json.rel, data:args,dialogId:json.dialogId,callback:dwzPageBreakCallback});
			}
		}
		if ("closeCurrent" == json.callbackType) {
			$.pdialog.closeCurrent();
		}
	}
}

function dialogAjaxTodo(url, callback){
	var $callback = callback || dialogAjaxDone;
	if (! $.isFunction($callback)) $callback = eval('(' + callback + ')');
	$.ajax({
		type:'POST',
		url:url,
		dataType:"json",
		cache: false,
		success: $callback,
		error: DWZ.ajaxError
	});
}